import { message } from 'ant-design-vue';
import { ref } from 'vue';

import { deserialize } from '@/plugins/reflect-metadata';

import { getAuthInfo, updateAuthInfo } from '../api';
import { AuthItem } from '../models/AuthItem';

const useAuthItem = () => {
  const params = ref(new AuthItem());
  const loading = ref(true);
  const actionLoading = ref(false);
  const handleFetch = async (dataId:string) => {
    try {
      loading.value = true;
      const { data } = await getAuthInfo(dataId);
      params.value = deserialize(data.data, AuthItem);
    } finally {
      loading.value = false;
    }
  };
  const handleUpdate = async () => {
    try {
      actionLoading.value = true;
      await updateAuthInfo(params.value);
      await handleFetch(params.value.meta.dataId);
      message.success('保存成功');
    } finally {
      actionLoading.value = false;
    }
  };
  return {
    params,
    loading,
    actionLoading,
    handleFetch,
    handleUpdate,
  };
};

export default useAuthItem;
